using APITransLib.Contracts;
using System.Net.Http.Json;

namespace ChatWithMultAI.ViewModels.Agent;

public interface IChatAgent
{
    Task<string> GenerateAsync(string prompt, CancellationToken ct = default);
    AgentProfileDto Profile { get; }
}

public class ChatAgent(HttpClient http, string ownerUserId) : IChatAgent
{
    public AgentProfileDto Profile { get; private set; } = new() { OwnerUserId = ownerUserId };

    public async Task InitializeAsync(CancellationToken ct = default)
    {
        var p = await http.GetFromJsonAsync<AgentProfileDto>($"api/agent/{ownerUserId}", ct);
        if (p is not null) Profile = p;
    }

    public async Task<string> GenerateAsync(string prompt, CancellationToken ct = default)
    {
        var req = new AgentGenerateRequest { Prompt = prompt };
        var res = await http.PostAsJsonAsync($"api/agent/{Profile.OwnerUserId}/generate", req, ct);
        res.EnsureSuccessStatusCode();
        var body = await res.Content.ReadFromJsonAsync<AgentGenerateResponse>(cancellationToken: ct);
        return body?.Reply ?? string.Empty;
    }
}
